package cn.bugstack.service.impl;

import cn.bugstack.common.constants.Constants;

import cn.bugstack.dao.IOrderDao;
import cn.bugstack.dao.IOrderItemsDao;
import cn.bugstack.dao.IProductDao;
import cn.bugstack.domain.Req.ShopCartReq;
import cn.bugstack.domain.po.OrderPO;
import cn.bugstack.domain.po.OrderProductPO;
import cn.bugstack.domain.po.PayOrder;
import cn.bugstack.domain.po.ProductDTO;
import cn.bugstack.domain.res.PayOrderRes;
import cn.bugstack.domain.vo.ProductVO;
import cn.bugstack.domain.vo.RecordingVO;
import cn.bugstack.service.IOrderService;
import cn.bugstack.service.rpc.ProductRPC;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.Product;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.google.common.eventbus.EventBus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class IOrderServiceImpl implements IOrderService {
    @Value("${alipay.notify_url}")
    private String notifyUrl;
    @Value("${alipay.return_url}")
    private String returnUrl;

    @Resource
    private IOrderDao orderDao;

//    @Resource
//    private ProductRPC productRPC;

    @Resource
    private IProductDao ProductDao;

    @Resource
    private IOrderItemsDao OrderItemsDao;

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private EventBus eventBus;

    @Override
    public PayOrderRes createOrder(ShopCartReq shopCartReq) throws AlipayApiException {
        //1.查询当前用户是否存在未支付订单或掉单订单
//        PayOrder payOrderReq = new PayOrder();
//        payOrderReq.setUserId(shopCartReq.getUserID());
//        payOrderReq.setProductId(shopCartReq.getProductIds());
//
//        PayOrder unpaidOrder = orderDao.queryUnPayOrder(payOrderReq);


//        OrderPO orderPO = new OrderPO();
//        orderPO.setUserId(shopCartReq.getUserID());
//        OrderPO unpaidOrder = orderDao.queryUnPayOrderPO(orderPO);
//        if (null != unpaidOrder && Constants.OrderStatusEnum.PAY_WAIT.getCode().equals(unpaidOrder.getStatus())){
//            log.info("创建订单-存在,已存在未支付订单。userId:{} productIds:{} orderId:{}",shopCartReq.getUserID(),shopCartReq.getProductIds(),unpaidOrder.getOrderId());
//            return PayOrderRes.builder()
//                    .orderId(unpaidOrder.getOrderId())
//                    .payUrl(unpaidOrder.getPayUrl())
//                    .build();
//        }else if (null != unpaidOrder && Constants.OrderStatusEnum.CREATE.getCode().equals(unpaidOrder.getStatus())){
//            log.info("创建订单-存在,存在未创建支付单订单,创建支付单开始 userId:{},productIds:{},orderId:{}",shopCartReq.getUserID(),shopCartReq.getProductIds(),unpaidOrder.getOrderId());
//            OrderPO order = doPrepayOrder(unpaidOrder.getOrderId(),unpaidOrder.getTotalAmount());
//            return PayOrderRes.builder()
//                    .orderId(order.getOrderId())
//                    .payUrl(order.getPayUrl())
//                    .build();
//        }

        //2.查询商品&创建订单
        List<ProductVO> productList = ProductDao.selectProductsByIds(shopCartReq.getProductIds());
        String orderId = RandomStringUtils.randomNumeric(16);

        BigDecimal totalAmount = new BigDecimal(0);
        for (ProductVO productVO : productList) {
            BigDecimal price = productVO.getPrice();
            totalAmount = totalAmount.add(price);
        }

        orderDao.insert(OrderPO.builder()
                        .userId(shopCartReq.getUserID())
                        .orderId(orderId)
                        .totalAmount(totalAmount)
                        .orderTime(new Date())
                        .status(Constants.OrderStatusEnum.CREATE.getCode())
                .build()
        );

        for (ProductVO productVO : productList) {
            OrderItemsDao.insert(ProductDTO.builder()
                    .orderId(orderId)
                    .userId(shopCartReq.getUserID())
                    .productId(productVO.getProductId())
                    .productName(productVO.getProductName())
                    .amount(productVO.getPrice())
                    .photo(productVO.getImageUrl())
                    .build());
        }

        //3.创建支付单
        OrderPO order = doPrepayOrder(orderId,totalAmount);

        return PayOrderRes.builder()
                .orderId(orderId)
                .payUrl(order.getPayUrl())
                .build();
    }

    @Override
    public void changeOrderPaySuccess(String orderId) {
        PayOrder payOrderReq = new PayOrder();
        payOrderReq.setOrderId(orderId);
        payOrderReq.setStatus(Constants.OrderStatusEnum.PAY_SUCCESS.getCode());
        orderDao.changeOrderPaySuccess(payOrderReq);

        eventBus.post(JSON.toJSONString(payOrderReq));
    }

    @Override
    public List<String> queryNoPayNotifyOrder() {
        return orderDao.queryNoPayNotifyOrder();
    }

    @Override
    public List<String> queryTimeoutCloseOrderList() {
        return orderDao.queryTimeoutCloseOrderList();
    }

    @Override
    public boolean changeOrderClose(String orderId) {
        return orderDao.changeOrderClose(orderId);
    }

    /**
     * 根据userId查询历史购买记录
     * @param userId
     */
    @Override
    public List<RecordingVO> queryHistoryOrder(String userId) {
        List<RecordingVO> recordingVOS = orderDao.selectHistoryOrder(userId);


        for (RecordingVO recordingVO : recordingVOS) {
            recordingVO.setUserId(userId);
            String orderId = recordingVO.getOrderId();
            String status = recordingVO.getStatus();
            if (Objects.equals(status, "CLOSE")){
                recordingVO.setPayTime(null);
            }
            List<OrderProductPO> orderProductPOS = orderDao.selectHistoryOrderItem(orderId);
            recordingVO.setProductList(orderProductPOS);
        }

        return recordingVOS;
    }

    @Override
    public boolean deleteOrder(String userId, String orderId) {
        return orderDao.deleteOrder(userId,orderId);
    }


    private OrderPO doPrepayOrder(String orderId, BigDecimal totalAmount) throws AlipayApiException {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        bizContent.put("total_amount", totalAmount.toString());
        bizContent.put("subject", orderId);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());

        String form = alipayClient.pageExecute(request).getBody();

        OrderPO orderPO = new OrderPO();
        orderPO.setOrderId(orderId);
        orderPO.setPayUrl(form);
        orderPO.setStatus(Constants.OrderStatusEnum.PAY_WAIT.getCode());

        orderDao.updateOrderPayInfo(orderPO);

        return orderPO;


    }



}
